﻿using fuzhu;
using LH.Model.Common;
using LH.Model.PU;
using LH.Model.ST;
using LH.U8API.Bus;
using Newtonsoft.Json;
using Org.BouncyCastle.Ocsp;
using RestSharp;
using SqlSuarEntity;
using SqlSugar;
using System.Data;
using System.Runtime.ConstrainedExecution;
using System.Text;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.GL;
using ZDEntity;
using ZDXieTong.Bo;
using static XXX.Models.WDFT.WDFT_SaleOrderJinDu;
using static XXX.Models.WMS.ScanBarcode;

namespace Yonyou.U8.BO
{
    //取glmodel，为来源参照
    public class NBHFSDCVM
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }

        public NBHF_BaoJian baoJian { get; set; }
        public NBHFSDCVM(string conStr)
        {
            this.conStr = conStr;
        }

        public RetModel2 XieTong(NBHF_XieTong entity)
        {
             if(entity == null)
            {
                return DBService.ReErrObject("没有传入数据");
              

            }
             if (entity.cLx=="到货报检")
            {
                if (entity.cOper=="add")
                {
                 return  PostBaoJian(entity.cCode); 
                }
                else if (entity.cOper == "verify")
                {
                    return PostBaoJianVerify(entity.cCode);
                }
                else if (entity.cOper == "del")
                {
                    return PostBaoJianDel("到货报检删除", entity.cCode);
                }
            }
             else if (entity.cLx == "生产订单")
            {
                if (entity.cOper == "add")
                {
                    return PostMorder(entity.cCode);
                    
                }
                if (entity.cOper == "del")
                {
                    return PostMorder(entity.cCode);

                }
            }
            else if (entity.cLx == "材料出库")
            {
                if (entity.cOper == "add")
                {
                    return PostRd11(entity.cCode);

                }
            }
            else if (entity.cLx == "调拨报检")
            {
                if (entity.cOper == "add")
                {
                    return PostTransVouch(entity.cCode);
                    
                }
                else if (entity.cOper == "del")
                {
                    return PostBaoJianDel("调拨报检删除", entity.cCode);
                }
                //20250408取消回写
                //else if (entity.cOper == "verify")
                //{
                //    return PostTransVouchVerify(entity.cCode);
                //}
            }
            else if (entity.cLx == "发货报检")
            {
                if (entity.cOper == "add")
                {
                    return PostDispatch(entity.cCode);

                }
                else if (entity.cOper == "del")
                {
                    return PostBaoJianDel("发货报检删除", entity.cCode);
                }
                //20250408取消回写
                //else if (entity.cOper == "verify")
                //{
                //    return PostDispatchVerify(entity.cCode);
                //}
            }
            if (entity.cLx == "all")
            {
                string cReInfo = "";
                //传入的是all，全部推送
                //生产订单推送
                string sql = string.Format(@"SELECT a.MoCode 
FROM mom_order a 
WHERE ISNULL(a.define10, '') = '' 
  AND a.createdate >= DATEADD(day, -1, CAST(GETDATE() AS DATE));  ");
                List<string> lstMoCode = SqlsugarHelper.Instance.Ado.SqlQuery<string>(sql);
                NBHFSDCVM nBHFSDCVM = new NBHFSDCVM(CanShu.conStr);
                for (int i = 0; i < lstMoCode.Count; i++)
                {
                    NBHF_XieTong nBHF_XieTong = new NBHF_XieTong();
                    nBHF_XieTong.cOper = "add";
                    nBHF_XieTong.cLx = "生产订单";
                    nBHF_XieTong.cCode = lstMoCode[i];
                    // 处理业务逻辑
                  RetModel2 ret = nBHFSDCVM.XieTong(nBHF_XieTong);
                    cReInfo += ret.message + "/r/n";
                    // 将 JSON 数据保存到数据库中
                    JsonSaveService.saveLog<NBHF_XieTong>(nBHF_XieTong, "XieTong", nBHF_XieTong.ToString(), ret.code, ret.message);
                }
                return DBService.ReOKObject(cReInfo);
            }

            return DBService.ReErrObject("未定义操作类型");
            



        }


        //SDCLogin
        #region SDCLogin
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">到货单号</param> 
        /// <returns></returns>
        public bool SDCLogin(string user,string pwd,out string acctoken)
        {
            try
            {


                NBHF_SDC_Login entity = new NBHF_SDC_Login();
                entity.account = user;
                entity.password = pwd;
                NBHF_SDC_ReConent cre = Post<NBHF_SDC_Login>("登陆", entity,user);
                if (cre.succeeded && !string.IsNullOrWhiteSpace(DbHelper.GetDbString(cre.data)))
                {
                    NBHF_SDC_LoginConent loginEntity  = JsonConvert.DeserializeObject<NBHF_SDC_LoginConent>(DbHelper.GetDbString(cre.data));
                    acctoken =  loginEntity.accessToken;
                    return true;
                }
                else
                {
                    acctoken = "";
                    return false;
                }

            }
            catch (Exception ex)
            {
                acctoken = ex.Message;
                return false;
            }

        }
        #endregion


        //推送到SDC
        #region 推送到SDC,到货单号
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">到货单号</param> 
        /// <returns></returns>
        public RetModel2 PostBaoJian(string cCode)
        {
            try
            {

                //查询主表，构建a.cMakeTime as  dDate
                string sql = string.Format(@"select a.cCode, a.cMakeTime as dDate,b.cInvCode,b.iQuantity,b.cBatch,a.cDefine10,a.cVenCode,a.cMaker,
case when isnull(cUserHand,'')='' then   cUser_Id else cUserHand end cUser_Id,b.cWhCode,b.cBatchProperty6
from PU_ArrivalVouch a
inner join PU_ArrivalVouchs b on a.id= b.id 
inner join inventory i on b.cinvcode= i.cinvcode
left join UFSystem..UA_User u on a.cMaker = u.cUser_Name
where  a.ccode='{0}' and i.cinvdefine2='是'  ", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst == null || lst.Count==0)
                {
                    var result = SqlsugarHelper.Instance.Updateable<PU_ArrivalVouch>()
                           .SetColumns(it => new PU_ArrivalVouch
                           {
                               cverifier = "SDC",
                               cAuditDate = DateTime.Now.Date,
                               caudittime = DateTime.Now,
                               iverifystateex = 2
                           }
                           )
                            .Where(it => it.cCode == cCode && (it.cverifier == ""  || it.cverifier == null))
                           .ExecuteCommand();

                    return  DBService.ReOKMsg("单据内没有需要检验的物料,直接审核");
                }
                else
                {
                    NBHF_BaoJian baoJian = new NBHF_BaoJian();
                    baoJian.billno = lst[0].cCode;
                    baoJian.billdate = lst[0].dDate.ToString("yyyy-MM-dd");
                    baoJian.Supplier = new NBHF_Suppiler();
                    baoJian.Supplier.code = lst[0].cVenCode;
                    baoJian.User = new NBHF_User();
                    baoJian.User.Account = lst[0].cUser_Id;
                    List<NBHF_BaoJianBody> details = new List<NBHF_BaoJianBody>();
                    foreach (var item in lst)
                    {
                        NBHF_BaoJianBody body = new NBHF_BaoJianBody();
                        body.material = new NBHF_Material();
                        body.material.Code = item.cInvCode;
                        body.batchno = item.cBatch;
                        body.supplierbatchno = item.cBatchProperty6;
                        body.qty = item.iQuantity;
                        body.warehouse = new NBHF_Material();
                        body.warehouse.Code = item.cWhCode;
                        body.id = 0;

                        details.Add(body);
                    }
                    baoJian.details = details;
                    string cType = "到货报检新增";
                    if (!string.IsNullOrEmpty(lst[0].cDefine10) &&  lst[0].cDefine10.Contains("新增推送成功"))
                    {
                        cType = "到货报检修改";
                    }
                    
                        NBHF_SDC_ReConent cre = Post<NBHF_BaoJian>(cType, baoJian, baoJian.billno);
                    
                    if (cre.succeeded)
                    {
                        if (cType == "到货报检新增")
                        {
                            sql = string.Format("update PU_ArrivalVouch set cDefine10='新增推送成功' where ccode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            sql = string.Format("update PU_ArrivalVouch set cDefine10='新增推送成功;修改推送成功' where ccode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }

                        return DBService.ReOKObject("推送成功！");
                    }
                    else
                    {
                        if (cType == "到货报检新增")
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 40)
                            {
                                cerr = cre.errors.Substring(0, 40);
                            }
                            sql = string.Format("update PU_ArrivalVouch set cDefine10='{1}' where ccode='{0}' ", cCode, "新增推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 20)
                            {
                                cerr = cre.errors.Substring(0, 20);
                            }
                            sql = string.Format("update PU_ArrivalVouch set cDefine10='新增推送成功;'+'{1}' where ccode='{0}' ", cCode, "修改推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReErrObject("推送失败：" + cre.errors);  
                    }
                 
                }
                 
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);   
            } 




        }
        #endregion


        // 到货单 ，审核检查
        #region  到货单，审核检查
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">到货单号</param> 
        /// <returns></returns>
        public RetModel2 PostBaoJianVerify(string cCode)
        {
            try
            {

                //查询主表，构建
                string sql = string.Format(@"select a.cCode,a.dDate,b.cInvCode,b.iQuantity,b.cBatch,a.cDefine10,a.cVenCode,a.cMaker,u.cUser_Id,b.cWhCode,b.cDefine25
from PU_ArrivalVouch a
inner join PU_ArrivalVouchs b on a.id= b.id 
inner join inventory i on b.cinvcode= i.cinvcode
left join UFSystem..UA_User u on a.cMaker = u.cUser_Name
where  a.ccode='{0}' and i.cinvdefine2='是' and  ( isnull(cDefine25,'')<>'合格'  and isnull(cDefine25,'')<>'不合格'  ) ", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst.Count>0)
                {
                    return DBService.ReErrObject("单据还未检验完成");
                }
                else
                {
                   
                    return DBService.ReOKObject("ok");
                  
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion


        // 到货单 ，删除检查
        #region  到货单，删除检查
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">到货单号</param> 
        /// <returns></returns>
        public RetModel2 PostBaoJianDel(string cType,string cCode)
        {
            try
            {
                NBHF_SDC_ReConent cre = Post<string>(cType, cCode, cCode);
               

                if (cre.succeeded )
                {
                    return DBService.ReOKObject("ok");
                }
                //错误信息内部包含单号不存在的，也被认为是可以删除
                else if   (cre.errors.Contains("不存在"))
                {
                        return DBService.ReOKObject("ok");
                 }
                    else
                {
                    if (cType == "到货报检删除")
                    {
                        string cerr = cre.errors;
                        if (cre.errors.Length > 40)
                        {
                            cerr = cre.errors.Substring(0, 40);
                        }
                        string sql = string.Format("update PU_ArrivalVouch set cDefine10='{1}' where ccode='{0}' ", cCode, "SDC删除失败：" + cerr);
                        SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                    }
                    else if (cType == "发货报检删除")
                    {
                        string cerr = cre.errors;
                        if (cre.errors.Length > 40)
                        {
                            cerr = cre.errors.Substring(0, 40);
                        }
                        string sql = string.Format("update rdrecord32 set cDefine10='{1}' where ccode='{0}' ", cCode, "SDC删除失败：" + cerr);
                        SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                    }
                    else if (cType == "调拨报检删除")
                    {
                        string cerr = cre.errors;
                        if (cre.errors.Length > 40)
                        {
                            cerr = cre.errors.Substring(0, 40);
                        }
                        string sql = string.Format("update transvouch set cDefine10='{1}' where ctvcode='{0}' ", cCode, "SDC删除失败：" + cerr);
                        SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                    }
                    return DBService.ReErrObject("SDC删除失败：" + cre.errors);
                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion


        #region 推送到SDC,生产订单 
        //推送到SDC
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">生产单号</param> 
        /// <returns></returns>
        public RetModel2 PostMorder(string cCode)
        {
            try
            {

                //查询主表，构建
                string sql = string.Format(@"select b.modid as autoid, a.MoCode+'-'+cast(b.sortseq  as varchar(50)) as  cCode,a.CreateDate as dDate,b.InvCode as cInvCode,b.Qty as iQuantity,
c.DueDate as  RequireDate,b.Define31 as  cDefine10,
(case when isnull(cUserHand,'')='' then   cUser_Id else cUserHand end) as cUser_Id,b.MoLotCode as cBatch
from mom_order a
inner join  mom_orderdetail b on  a.MoId= b.MoId
inner join  mom_morder c  on   b.moDid= c.moDid
left join UFSystem..UA_User u on a.CreateUser = u.cUser_Id
where  a.MoCode='{0}'", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst == null || lst.Count==0)
                {
                    return DBService.ReErrObject("单据号错误");
                }
                else
                {
                    string cReInfo = "";
                    for(int i=0;i<lst.Count;i++)
                    {
                        NBHF_Morder morder = new NBHF_Morder();
                        morder.Code = lst[i].cCode;
                        morder.WODate = lst[i].dDate.ToString("yyyy-MM-dd");
                        morder.Material = new NBHF_Material();
                        morder.Material.Code = lst[i].cInvCode;
                        morder.RequiredEndDate = DbHelper.GetDbDate(lst[0].RequireDate).ToString("yyyy-MM-dd");
                        morder.MFGQty = lst[i].iQuantity;
                        morder.Originator = new NBHF_User();
                        morder.Originator.Account = lst[0].cUser_Id;
                        morder.ProjectCode = "";
                        morder.BatchNo = lst[i].cBatch;
                        //读取子件材料信息
                        int autoid = lst[i].autoid;
                        sql = string.Format(@"select InvCode as cInvCode,Qty as TotalQuantity ,com.cComUnitName,a.BaseQtyN/BaseQtyD as iQuantity   from mom_moallocate  a
inner join inventory i on a.InvCode = i.cInvCode 
inner join ComputationUnit com on i.ccomunitcode = com.ccomunitcode where  moDid='{0}'", autoid);
                        List<NBHF_Record> lstdetail = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();

                        List<NBHF_MorderBody> details = new List<NBHF_MorderBody>();
                        foreach (var item in lstdetail)
                        {
                            NBHF_MorderBody body = new NBHF_MorderBody();
                            body.Code = item.cInvCode;
                            body.Quantity = DbHelper.GetDbdecimal(item.iQuantity);
                            body.TotalQuantity = DbHelper.GetDbdecimal(item.TotalQuantity);
                            body.Uint = item.cComUnitName;
                            body.Id = 0;

                            details.Add(body);
                        }
                        morder.WorkOrderErpBoms = details;

                        string cType = "生产订单新增";
                        if (!string.IsNullOrEmpty(lst[i].cDefine10) && lst[i].cDefine10.Contains("新增推送成功"))
                        {
                            cType = "生产订单修改";
                        }
                        NBHF_SDC_ReConent cre = Post<NBHF_Morder>(cType, morder, morder.Code);
                        if (cre.succeeded)
                        {
                            if (cType == "生产订单新增")
                            {
                                sql = string.Format("update mom_orderdetail set Define31='新增推送成功' where modid='{0}' ", autoid);
                                SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                            }
                            else
                            {
                                sql = string.Format("update mom_orderdetail set Define31='新增推送成功;修改推送成功' where modid='{0}' ", autoid);
                                SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                            }

                            cReInfo += morder.Code+"推送成功;";
                        }
                        else
                        {
                            if (cType == "生产订单新增")
                            {
                                string cerr = cre.errors;
                                if (cre.errors.Length > 40)
                                {
                                    cerr = cre.errors.Substring(0, 40);
                                }
                                sql = string.Format("update mom_orderdetail set Define31='{1}' where modid='{0}' ", autoid, "新增推送失败：" + cerr);
                                SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                            }
                            else
                            {
                                string cerr = cre.errors;
                                if (cre.errors.Length > 20)
                                {
                                    cerr = cre.errors.Substring(0, 20);
                                }
                                sql = string.Format("update mom_orderdetail set Define31='新增推送成功;'+'{1}' where modid='{0}' ", cCode, "修改推送失败：" + cerr);
                                SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                            }
                            cReInfo += morder.Code + "推送失败：" + cre.errors + ";"; 
                        }
                    }
                    if (cReInfo.Contains("失败"))
                    {
                        return DBService.ReErrObject(cReInfo);
                    }
                   else
                    {
                        return DBService.ReOKObject(cReInfo);
                    }
                  
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion


        #region 推送到SDC,工单领料 
        //推送到SDC
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">生产单号</param> 
        /// <returns></returns>
        public RetModel2 PostRd11(string cCode)
        {
            try
            {

                //查询主表，构建
                string sql = $@" select  a.cCode, b.autoid, a.dDate,b.cInvCode,b.iQuantity,b.cBatch,b.cMoCode+'-'+cast(b.imoseq as varchar(50)) as cMoCode,b.cdefine31,com.cComUnitName from rdrecord11 a
 inner join  rdrecords11 b  on a.id= b.id 
 inner join  inventory inv on b.cinvcode=inv.cinvcode
 inner join computationUnit com on inv.ccomunitcode = com.ccomunitcode
and a.cCode='{cCode}' and isnull( cMoCode,'')<>'' and isnull(cdefine31,'')<>'推送成功' " ;
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst == null || lst.Count == 0)
                {
                    return DBService.ReErrObject(" 生产订单出库或者未推送的才可以推送");
                }
                else
                {
                    
                    // lst 是您的原始列表
                    var groupedRecords = lst.GroupBy(record => record.cMoCode);

                    // 如果您需要将每个分组转换为一个列表，可以这样做：
                    var listOfGroupedLists = groupedRecords.ToDictionary(
                        group => group.Key, // 分组键，即 cMoCode 的值
                        group => group.ToList() // 将分组中的元素转换为 List<NBHF_Record>
                    );
                    string cRe = "";
                    foreach (var group in groupedRecords)
                    {
                        Console.WriteLine($"Group: {group.Key}");
                    
                        foreach (var record in group)
                        {
                            NBHF_Rd11 entity = new NBHF_Rd11();
                            //取生产订单号
                            entity.Code = record.cMoCode;
                            List<NBHF_Rd11Body> materialPicking = new List<NBHF_Rd11Body>();
                            NBHF_Rd11Body nBHF_Rd11Body = new NBHF_Rd11Body();
                            nBHF_Rd11Body.Material = new NBHF_Material();
                            nBHF_Rd11Body.Material.Code = record.cInvCode;
                            nBHF_Rd11Body.Quantity = record.iQuantity;
                            nBHF_Rd11Body.BatchNo = record.cBatch; 
                            materialPicking.Add(nBHF_Rd11Body);
                            entity.MaterialPicking = materialPicking;
                          
                            NBHF_SDC_ReConent cre1 = Post<NBHF_Rd11>("工单领料新增", entity, entity.Code);
                            if (cre1.succeeded)
                            {
                                sql = string.Format(@"update rdrecords11 set cDefine31='推送成功' from rdrecord11 a,rdrecords11 b
where a.id = b.id and  a.ccode='{0}' and b.cinvcode='{2}' and  b.cMoCode+'-'+cast(b.imoseq as varchar(50))='{1}'   ", cCode, entity.Code, record.cInvCode);
                                SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                                cRe += entity.Code+"推送成功;";
                            }
                            else
                            {
                                sql = string.Format(@"update rdrecords11 set cDefine31='推送失败'+'{3}' from rdrecord11 a,rdrecords11 b
where a.id = b.id and  a.ccode='{0}' and b.cinvcode='{2}' and  b.cMoCode+'-'+cast(b.imoseq as varchar(50))='{1}'   ", cCode, entity.Code, record.cInvCode, cre1.errors);
                                SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                                cRe += entity.Code + "推送失败：" + cre1.errors+";";
                            } 

                        }
                    } 
                    if (cRe.Contains("失败"))
                    {
                     return    DBService.ReErrObject(cRe);
                    }
                    else
                    {
                        return DBService.ReErrObject(cRe);
                    } 
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion


        #region 推送到SDC,调拨单更改成调拨申请单
        //推送到SDC
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">生产单号</param> 
        /// <returns></returns>
        public RetModel2 PostTransVouch(string cCode)
        {
            try
            {

                //查询主表，构建 and i.cinvdefine2='是'
                //user使用手机号码
                string sql = string.Format(@"select  a.cTVCode as  cCode,a.dTVDate as dDate,cDefine10,b.cInvCode,b.iTVQuantity as iQuantity,b.cTVBatch AS cBatch,a.cOWhCode as cOWhCode,cIWhCode as cIWhCode,a.cMaker,
case when isnull(cUserHand,'')='' then   cUser_Id else cUserHand end as cUser_Id,b.cDefine25 as QualityStatus
from TransVouch a
inner join TransVouchs b  on a.ID= b.id  
inner join inventory i on b.cinvcode= i.cinvcode
left join UFSystem..UA_User u on a.cMaker = u.cUser_Name
where a.cTVCode='{0}'  and isnull(a.cverifyperson,'')<>'' ", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst == null || lst.Count == 0)
                {
                    return DBService.ReErrObject("单据内没有需要检验的物料");
                }
                else
                {
                    string cRe = "";
                    NBHF_TranVouch entity = new NBHF_TranVouch();

                    entity.Billno = lst[0].cCode;
                    entity.BillDate = DbHelper.GetDbDate(lst[0].dDate).ToString("yyyy-MM-dd");
                    entity.Operator = new NBHF_User();
                    entity.Operator.Account = lst[0].cUser_Id;

                    List<NBHF_TransVouchBody> lstdetail = new List<NBHF_TransVouchBody>();
                    NBHF_TransVouchBody nBHF_Rd11Body = new NBHF_TransVouchBody();
                    foreach (var record in lst)
                    {
                        nBHF_Rd11Body.Material = new NBHF_Material();
                        nBHF_Rd11Body.Material.Code = record.cInvCode;
                        nBHF_Rd11Body.Qty = record.iQuantity;
                        nBHF_Rd11Body.BatchNo = record.cBatch;
                        nBHF_Rd11Body.OutWarehouse = new NBHF_Material();
                        nBHF_Rd11Body.OutWarehouse.Code = record.cOWhCode;
                        nBHF_Rd11Body.InWarehouse = new NBHF_Material();
                        nBHF_Rd11Body.InWarehouse.Code = record.cIWhCode;
                        if (record.QualityStatus != "合格")
                        {
                            nBHF_Rd11Body.QualityStatus = new QualityStatus();
                            nBHF_Rd11Body.QualityStatus.Code = "02";
                        }
                        else
                        {
                            nBHF_Rd11Body.QualityStatus = new QualityStatus();
                            nBHF_Rd11Body.QualityStatus.Code = "04";
                        }
                        lstdetail.Add(nBHF_Rd11Body);
                    }

                    entity.Details = lstdetail;
                    string cType = "库存调拨新增";
                    if (!string.IsNullOrEmpty(lst[0].cDefine10) && lst[0].cDefine10.Contains("新增推送成功"))
                    {
                        cType = "库存调拨修改";
                    }
                    NBHF_SDC_ReConent cre = Post<NBHF_TranVouch>(cType, entity, entity.Billno);
                    if (cre.succeeded)
                    {
                        if (cType == "库存调拨新增")
                        {
                            sql = string.Format("update TransVouch set cDefine10='新增推送成功' where cTVCode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            sql = string.Format("update TransVouch set cDefine10='新增推送成功;修改推送成功' where cTVCode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReOKObject("推送成功！");
                    }
                    else
                    {
                        if (cType == "库存调拨新增")
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 40)
                            {
                                cerr = cre.errors.Substring(0, 40);
                            }
                            sql = string.Format("update TransVouch set cDefine10='{1}' where cTVCode='{0}' ", cCode, "新增推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length>20)
                            {
                                cerr = cre.errors.Substring(0,20);
                            }
                            sql = string.Format("update TransVouch set cDefine10='新增推送成功;'+'{1}' where cTVCode='{0}' ", cCode, "修改推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReErrObject("推送失败：" + cre.errors);
                    }


                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion

        #region 推送到SDC,调拨单更改成调拨申请单，不用了 
        //推送到SDC
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">生产单号</param> 
        /// <returns></returns>
        public RetModel2 PostTransVouchApp(string cCode)
        {
            try
            {

                //查询主表，构建
                string sql = string.Format(@"select  a.cTVCode as  cCode,a.dTVDate as dDate,cDefine10,b.cInvCode,b.iTVQuantity as iQuantity,b.cTVBatch AS cBatch,a.cOWhCode as cOWhCode,cIWhCode as cIWhCode,a.cMaker,
case when isnull(cUserHand,'')='' then   cUser_Id else cUserHand end as cUser_Id,b.cDefine25 as QualityStatus
from ST_AppTransVouch a
inner join ST_AppTransVouchs b  on a.ID= b.id  
inner join inventory i on b.cinvcode= i.cinvcode
left join UFSystem..UA_User u on a.cMaker = u.cUser_Name
where a.cTVCode='{0}' and i.cinvdefine2='是'  ", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst == null || lst.Count == 0)
                {
                    return DBService.ReErrObject("单据内没有需要检验的物料");
                }
                else
                {
                    string cRe = "";
                    NBHF_TranVouch entity = new NBHF_TranVouch();

                    entity.Billno = lst[0].cCode;
                    entity.BillDate = DbHelper.GetDbDate(lst[0].dDate).ToString("yyyy-MM-dd");
                    entity.Operator = new NBHF_User();
                    entity.Operator.Account = lst[0].cUser_Id;

                    List<NBHF_TransVouchBody> lstdetail = new List<NBHF_TransVouchBody>();
                    NBHF_TransVouchBody nBHF_Rd11Body = new NBHF_TransVouchBody();
                    foreach (var record in lst)
                    {
                        nBHF_Rd11Body.Material = new NBHF_Material();
                        nBHF_Rd11Body.Material.Code = record.cInvCode;
                        nBHF_Rd11Body.Qty = record.iQuantity;
                        nBHF_Rd11Body.BatchNo = record.cBatch;
                        nBHF_Rd11Body.OutWarehouse = new NBHF_Material();
                        nBHF_Rd11Body.OutWarehouse.Code = record.cOWhCode;
                        nBHF_Rd11Body.InWarehouse = new NBHF_Material();
                        nBHF_Rd11Body.InWarehouse.Code = record.cIWhCode;
                        if (record.QualityStatus != "已检验")
                        {
                            nBHF_Rd11Body.QualityStatus = new QualityStatus();
                            nBHF_Rd11Body.QualityStatus.Code = "02";
                        }
                        else
                        {
                            nBHF_Rd11Body.QualityStatus = new QualityStatus();
                            nBHF_Rd11Body.QualityStatus.Code = "04";
                        }
                        lstdetail.Add(nBHF_Rd11Body);
                    }

                    entity.Details = lstdetail;
                    string cType = "库存调拨新增";
                    if (!string.IsNullOrEmpty(lst[0].cDefine10) && lst[0].cDefine10.Contains("新增推送成功"))
                    {
                        cType = "库存调拨修改";
                    }
                    NBHF_SDC_ReConent cre = Post<NBHF_TranVouch>(cType, entity, entity.Billno);
                    if (cre.succeeded)
                    {
                        if (cType == "库存调拨新增")
                        {
                            sql = string.Format("update ST_AppTransVouch set cDefine10='新增推送成功' where cTVCode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            sql = string.Format("update ST_AppTransVouch set cDefine10='新增推送成功;修改推送成功' where cTVCode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReOKObject("推送成功！");
                    }
                    else
                    {
                        if (cType == "库存调拨新增")
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 40)
                            {
                                cerr = cre.errors.Substring(0, 40);
                            }
                            sql = string.Format("update ST_AppTransVouch set cDefine10='{1}' where cTVCode='{0}' ", cCode, "新增推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 20)
                            {
                                cerr = cre.errors.Substring(0, 20);
                            }
                            sql = string.Format("update ST_AppTransVouch set cDefine10='新增推送成功;'+'{1}' where cTVCode='{0}' ", cCode, "修改推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReErrObject("推送失败：" + cre.errors);
                    }


                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion

        #region  调拨单，审核检查，不用了

        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">到货单号</param> 
        /// <returns></returns>
        public RetModel2 PostTransVouchVerify(string cCode)
        {
            try
            {

                //查询主表，构建
                string sql = string.Format(@"select  a.cTVCode as  cCode,a.dTVDate as dDate,b.cInvCode,b.iTVQuantity as iQuantity,b.cTVBatch AS cBatch,a.cOWhCode as cOWhCode,cIWhCode as cIWhCode,a.cMaker,
case when isnull(cUserHand,'')='' then   cUser_Id else cUserHand end as cUser_Id
from TransVouch a
inner join TransVouchs b  on a.ID= b.id  
inner join inventory i on b.cinvcode= i.cinvcode
left join UFSystem..UA_User u on a.cMaker = u.cUser_Name
where a.cTVCode='{0}' and i.cinvdefine2='是'  and isnull(cDefine25,'')<>'已检验'  ", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst.Count > 0)
                {
                    return DBService.ReErrObject("单据还未检验完成");
                }
                else
                {

                    return DBService.ReOKObject("ok");

                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion

        #region 推送到SDC,发货单，20250408 更改成销售出库单
        //推送到SDC
        /// <summary>
        /// 发货单
        /// </summary>
        /// <param name="cCode">生产单号</param> 
        /// <returns></returns>
        public RetModel2 PostDispatch_作废(string cCode)
        {
            try
            {

                //查询主表，构建
                string sql = string.Format(@"select  a.cDLCode as  cCode,a.dDate as dDate,b.cInvCode,b.iQuantity as iQuantity,a.cDefine10,b.cBatch AS cBatch,a.cMaker,
case when isnull(cUserHand,'')='' then   cUser_Id else cUserHand end as cUser_Id  ,b.cWhCode,b.cDefine25 as QualityStatus from DispatchList a
inner join DispatchLists b  on a.DLID= b.DLID
inner join inventory i on b.cinvcode= i.cinvcode
left join UFSystem..UA_User u on a.cMaker = u.cUser_Name
where a.cDLCode='{0}' and i.cinvdefine2='是' ", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst == null || lst.Count == 0)
                {

                    var result = SqlsugarHelper.Instance.Updateable<DispatchList>()
                           .SetColumns(it => new DispatchList
                           {
                               cVerifier = "SDC",
                               dverifydate = DateTime.Now.Date,
                               dverifysystime = DateTime.Now,
                           }
                           )
                            .Where(it => it.cDLCode == cCode && (it.cVerifier == "" || it.cVerifier == null))
                           .ExecuteCommand();
                    

                    return DBService.ReOKMsg("单据内没有需要检验的物料,直接审核"); 
                }
                else
                {
                    string cRe = "";
                    NBHF_Dispatchlist entity = new NBHF_Dispatchlist();

                    entity.billno = lst[0].cCode;
                    entity.billdate = DbHelper.GetDbDate(lst[0].dDate).ToString("yyyy-MM-dd");
                    entity.Person = new NBHF_User();
                    entity.Person.Account = lst[0].cUser_Id;

                    List<NBHF_DispatchlistBody> lstdetail = new List<NBHF_DispatchlistBody>();
                    NBHF_DispatchlistBody nBHF_Rd11Body = new NBHF_DispatchlistBody();
                    foreach (var record in lst)
                    {
                        nBHF_Rd11Body.Material = new NBHF_Material();
                        nBHF_Rd11Body.Material.Code = record.cInvCode;
                        nBHF_Rd11Body.Qty = record.iQuantity;
                        nBHF_Rd11Body.BatchNo = record.cBatch;
                        nBHF_Rd11Body.Warehouse = new NBHF_Material();
                        nBHF_Rd11Body.Warehouse.Code = record.cWhCode;
                        if (record.QualityStatus!= "已检验")
                        {
                            nBHF_Rd11Body.QualityStatus = new QualityStatus();
                            nBHF_Rd11Body.QualityStatus.Code = "02";
                        }
                        else
                        {
                            nBHF_Rd11Body.QualityStatus = new QualityStatus();
                            nBHF_Rd11Body.QualityStatus.Code = "04";
                        }
                        lstdetail.Add(nBHF_Rd11Body);
                    }

                    entity.details = lstdetail;
                    string cType = "销售发货新增";
                    if (!string.IsNullOrEmpty(lst[0].cDefine10) && lst[0].cDefine10.Contains("新增推送成功"))
                    {
                        cType = "销售发货修改";
                    }

                    NBHF_SDC_ReConent cre = Post<NBHF_Dispatchlist>(cType, entity, entity.billno);
                    if (cre.succeeded)
                    {
                        if (cType == "销售发货新增")
                        {
                            sql = string.Format("update DispatchList set cDefine10='新增推送成功' where cDLCode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            sql = string.Format("update DispatchList set cDefine10='新增推送成功;修改推送成功' where cDLCode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReOKObject("推送成功！");
                    }
                    else
                    {
                        if (cType == "销售发货新增")
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 40)
                            {
                                cerr = cre.errors.Substring(0, 40);
                            }
                            sql = string.Format("update DispatchList set cDefine10='{1}' where cDLCode='{0}' ", cCode, "新增推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 20)
                            {
                                cerr = cre.errors.Substring(0, 20);
                            }
                            sql = string.Format("update DispatchList set cDefine10='新增推送成功;'+'{1}' where cDLCode='{0}' ", cCode, "修改推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReErrObject("推送失败：" + cre.errors);
                    }


                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion


        #region 推送到SDC,发货单，20250408 更改成销售出库单
        //推送到SDC
        /// <summary>
        /// 发货单
        /// </summary>
        /// <param name="cCode">销售出库单号</param> 
        /// <returns></returns>
        public RetModel2 PostDispatch(string cCode)
        {
            try
            {

                //查询主表，构建, 传审核后的数据  and i.cinvdefine2='是'
                string sql = string.Format(@"select  a.cCode,a.dDate as dDate,b.cInvCode,b.iQuantity as iQuantity,a.cDefine10,b.cBatch AS cBatch,a.cMaker,
case when isnull(cUserHand,'')='' then   cUser_Id else cUserHand end as cUser_Id  ,a.cWhCode,b.cDefine25 as QualityStatus 
from rdrecord32 a
inner join rdrecords32 b  on a.ID= b.ID
inner join inventory i on b.cinvcode= i.cinvcode
left join UFSystem..UA_User u on a.cMaker = u.cUser_Name
where a.cCode='{0}'  and isnull(a.chandler,'')<>'' ", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst == null || lst.Count == 0)
                { 
                    return DBService.ReOKMsg("单据内没有需要检验的物料,直接审核");
                }
                else
                {
                    string cRe = "";
                    NBHF_Dispatchlist entity = new NBHF_Dispatchlist();

                    entity.billno = lst[0].cCode;
                    entity.billdate = DbHelper.GetDbDate(lst[0].dDate).ToString("yyyy-MM-dd");
                    entity.Person = new NBHF_User();
                    entity.Person.Account = lst[0].cUser_Id;

                    List<NBHF_DispatchlistBody> lstdetail = new List<NBHF_DispatchlistBody>();
                    NBHF_DispatchlistBody nBHF_Rd11Body = new NBHF_DispatchlistBody();
                    foreach (var record in lst)
                    {
                        nBHF_Rd11Body.Material = new NBHF_Material();
                        nBHF_Rd11Body.Material.Code = record.cInvCode;
                        nBHF_Rd11Body.Qty = record.iQuantity;
                        nBHF_Rd11Body.BatchNo = record.cBatch;
                        nBHF_Rd11Body.Warehouse = new NBHF_Material();
                        nBHF_Rd11Body.Warehouse.Code = record.cWhCode;
                        if (record.QualityStatus != "合格")
                        {
                            nBHF_Rd11Body.QualityStatus = new QualityStatus();
                            nBHF_Rd11Body.QualityStatus.Code = "02";
                        }
                        else
                        {
                            nBHF_Rd11Body.QualityStatus = new QualityStatus();
                            nBHF_Rd11Body.QualityStatus.Code = "04";
                        }
                        lstdetail.Add(nBHF_Rd11Body);
                    }

                    entity.details = lstdetail;
                    string cType = "销售发货新增";
                    if (!string.IsNullOrEmpty(lst[0].cDefine10) && lst[0].cDefine10.Contains("新增推送成功"))
                    {
                        cType = "销售发货修改";
                    }

                    NBHF_SDC_ReConent cre = Post<NBHF_Dispatchlist>(cType, entity, entity.billno);
                    if (cre.succeeded)
                    {
                        if (cType == "销售发货新增")
                        {
                            sql = string.Format("update rdrecord32 set cDefine10='新增推送成功' where cCode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            sql = string.Format("update rdrecord32 set cDefine10='新增推送成功;修改推送成功' where cCode='{0}' ", cCode);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReOKObject("推送成功！");
                    }
                    else
                    {
                        if (cType == "销售发货新增")
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 40)
                            {
                                cerr = cre.errors.Substring(0, 40);
                            }
                            sql = string.Format("update rdrecord32 set cDefine10='{1}' where cCode='{0}' ", cCode, "新增推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        else
                        {
                            string cerr = cre.errors;
                            if (cre.errors.Length > 20)
                            {
                                cerr = cre.errors.Substring(0, 20);
                            }
                            sql = string.Format("update rdrecord32 set cDefine10='新增推送成功;'+'{1}' where cCode='{0}' ", cCode, "修改推送失败：" + cerr);
                            SqlsugarHelper.Instance.Ado.ExecuteCommand(sql);
                        }
                        return DBService.ReErrObject("推送失败：" + cre.errors);
                    }


                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion

        #region  发货单，审核检查
        /// <summary>
        /// 发货单
        /// </summary>
        /// <param name="cCode">到货单号</param> 
        /// <returns></returns>
        public RetModel2 PostDispatchVerify(string cCode)
        {
            try
            {

                //查询主表，构建
                string sql = string.Format(@"select  a.cDLCode as  cCode,a.dDate as dDate,b.cInvCode,b.iQuantity as iQuantity,b.cBatch AS cBatch,a.cMaker,u.cUser_Id,b.cWhCode,b.cDefine25 as QualityStatus from DispatchList a
inner join DispatchLists b  on a.DLID= b.DLID
inner join inventory i on b.cinvcode= i.cinvcode
left join UFSystem..UA_User u on a.cMaker = u.cUser_Name
where a.cDLCode='{0}' and i.cinvdefine2='是'   and isnull(cDefine25,'')<>'合格'  ", cCode);
                List<NBHF_Record> lst = SqlsugarHelper.Instance.Ado.SqlQuery<NBHF_Record>(sql).ToList();
                if (lst.Count > 0)
                {
                    return DBService.ReErrObject("单据还未检验完成");
                }
                else
                {

                    return DBService.ReOKObject("ok");

                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion

        #region 推送到SDC,工单领料 删除
        //推送到SDC
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="cCode">生产单号</param> 
        /// <returns></returns>
        public string PostRd11_Del(string cCode)
        {
            try
            {
                string cRe = "";
                 
                            NBHF_Rd11 entity = new NBHF_Rd11();
                            //取生产订单号
                            entity.Code = cCode;
                            NBHF_SDC_ReConent cre1 = Post<NBHF_Rd11>("工单领料删除", entity, entity.Code);

                if (cre1.succeeded)
                {
                    cRe += entity.Code + "删除成功;";
                }
                else
                {
                    cRe += entity.Code + "删除失败" + cre1.errors + ";";
                }

                return cRe;
                

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
              
        }
        #endregion


        #region 推送到SDC
        /// <summary>
        /// 推送到SDC,返回ok或者error
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="err">错误信息</param>
        /// <param name="id">新增单据的id</param>
        /// <param name="ccode">新增单据的code</param>
        /// <returns></returns>
        private NBHF_SDC_ReConent Post<T>(string cType,T entity,string cCode)
        {
            try
            {
                string Url =""; 
                switch (cType)
                {
                    case "登陆":
                        Url = "/api/rbac/login";
                        break;
                    case "到货报检新增":
                        Url = "/api/pur/addpurchasestockin";                       
                        break; 
                    case "到货报检修改":
                        Url = "/api/pur/updatepurchasestockin";
                        break;
                    case "生产订单新增":
                        Url = "/api/mfg/addworkorder";
                        break;
                    case "生产订单修改":
                        Url = "/api/mfg/updateworkorder";
                        break;
                    case "工单领料新增":
                        Url = "/api/mfg/addmaterialpicking";
                        break;
                    case "工单领料删除":
                        Url = "/api/mfg/deletematerialpicking";
                        break;
                    case "库存调拨新增":
                        Url = "/api/stk/addstktransfer";
                        break;
                    case "库存调拨修改":
                        Url = "/api/stk/updatestktransferhf";
                        break;
                    case "销售发货新增":
                        Url = "/api/stk/addsaleoutstock";
                        break;
                    case "销售发货修改":
                        Url = "/api/stk/addsaleoutstockhf";
                        break;
                    case "到货报检删除":
                        Url = "/api/pur/candeletepurchasestockin";
                        break;
                    case "调拨报检删除":
                        Url = "/api/stk/candeletestktransfer";
                        break;
                    case "发货报检删除":
                        Url = "/api/stk/candeletesaleoutstock";
                        break;
                    default:
                        break;
                }
                

                string json = JsonConvert.SerializeObject(entity);
                //如果是登陆，不需要开始获取token。 其他接口，先调用登陆，获取token
                if (cType == "登陆")
                {
                    string rest = WebPostService.PostWMS(CanShu.MesUrl + Url, json,"");
                    NBHF_SDC_ReConent reEntity = JsonConvert.DeserializeObject<NBHF_SDC_ReConent>(rest);
                    //JsonSaveService.saveLog2(cType, cCode, json, reEntity.statusCode, rest);
                    return reEntity;
                }
               
                else
                {
                    string acctoken = "";
                   if ( SDCLogin(CanShu.MESUser.userid, CanShu.MESUser.password,out acctoken))
                    {

                         if (cType == "到货报检删除" || cType == "调拨报检删除" || cType == "发货报检删除")
                        {
                            Url =  Url + "/" + entity.ToString() ;
 
                        }


                        string rest = WebPostService.PostWMS(CanShu.MesUrl + Url, json, acctoken);
                        // 将 JSON 数据保存到数据库中
                        //JsonSaveService.saveLog2(cType, cCode, json, 0, rest);
                        LoggerHelper logger = new LoggerHelper();
                        logger.Info("", cType+"发起：" + json);
                        logger.Info("", cType+"返回：" +rest );
                        NBHF_SDC_ReConent reEntity = JsonConvert.DeserializeObject<NBHF_SDC_ReConent>(rest);

                        JsonSaveService.saveLog2(cType, cCode, json, reEntity.statusCode, rest);

                        return reEntity;
                    }
                   else
                    {
                        return new NBHF_SDC_ReConent() { statusCode = 500, errors = "登录失败" };
                    }
                }
              

            }
            catch (Exception ex)
            {
                return new NBHF_SDC_ReConent() { statusCode = 500, errors = ex.Message }; 
            }
        }

        #endregion


        #region 推送到SDC
        /// <summary>
        /// 推送到SDC,返回ok或者error
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="err">错误信息</param>
        /// <param name="id">新增单据的id</param>
        /// <param name="ccode">新增单据的code</param>
        /// <returns></returns>
        private NBHF_SDC_ReConent Get<T>(string cType, T entity)
        {
            try
            {
                string Url = "";
                switch (cType)
                {
                    case "工单设备":
                        Url = "/api/mfg/getworkorderequipment";
                        break;
                    case "工时":
                        Url = "/api/mfg/getproductionreport";
                        break; 
                    default:
                        break;
                }
                string acctoken = "";
                if (SDCLogin(CanShu.MESUser.userid, CanShu.MESUser.password, out acctoken))
                {
                    if (cType == "工单设备")
                    {
                        string json = JsonConvert.SerializeObject(entity);
                        string rest = WebPostService.GetSDC(CanShu.MesUrl + Url, json, acctoken);
                        NBHF_SDC_ReConent reEntity = JsonConvert.DeserializeObject<NBHF_SDC_ReConent>(rest);
                        return reEntity;
                    }
                    else
                    {
                        string json = "";
                        string rest = WebPostService.GetSDC(CanShu.MesUrl + Url + "/" + entity.ToString(), json, acctoken);

                        NBHF_SDC_ReConent reEntity = JsonConvert.DeserializeObject<NBHF_SDC_ReConent>(rest);
                        return reEntity;
                    }
                }
                else
                {
                    return new NBHF_SDC_ReConent() { statusCode = 500, errors = "登录失败" };
                }

                

            }
            catch (Exception ex)
            {
                return new NBHF_SDC_ReConent() { statusCode = 500, errors = "错误："+ ex.Message };
               
            }
        }

        #endregion


        #region 到货单检验结果返回
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="model">检验结果</param> 
        /// <returns></returns>
        public RetModel2 PuArrQC(NBHF_QCCheck model)
        {
            try
            {
                if (model==null)
                {
                    throw new Exception("传入参数为空，错误");
                }
                if(model.itemList ==null)
                {
                    throw new Exception("没有检验明细，错误");
                }
                if (model.itemList.Count == 0)
                {
                    throw new Exception("没有检验明细，参数错误");
                }
               
                //查询主表，构建
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                { 
                    foreach (var item in model.itemList)
                    {
                        //到货单号
                        string cCode = item.cArrCode;
                        if (string.IsNullOrEmpty(cCode))
                        {
                            throw new Exception("到货单号不能为空");
                        }

                        PU_ArrivalVouch vouch = db.Queryable<PU_ArrivalVouch>().Where(x => x.cCode == cCode).First();
                        if (vouch == null)
                        {
                            throw new Exception("单据号错误");
                        }
                        //else if (!string.IsNullOrEmpty(vouch.cverifier))
                        //{
                        //    throw new Exception("单据已审核");
                        //}
                        else
                        {

                            //已拒收数量为基准进行反算
 
         //                   var result = db.Updateable<PU_ArrivalVouchs>()
         //.SetColumns(it=>new PU_ArrivalVouchs
         //{
         //    fRefuseQuantity = item.fRefuseQuantity,
         //    fRealQuantity = it.iQuantity - item.fRefuseQuantity,
         //    fValidQuantity = it.iQuantity - item.fRefuseQuantity,
         //    cDefine25 = "已检验"
         //})
         //.Where(it => it.ID == vouch.ID && it.cInvCode == item.cInvCode && (it.cBatch ?? "") == (item.cBatch ?? ""))
         //.ExecuteCommand();

                            //只回写到表体自定义项8
                            var result = db.Updateable<PU_ArrivalVouchs>()
        .SetColumns(it => new PU_ArrivalVouchs
        {
            cDefine27 = (double?)item.fDamageQuantity, 
            cDefine25 = item.fRefuseQuantity>0?"不合格":"合格",
            fRefuseQuantity = item.fRefuseQuantity > 0 ? it.iQuantity : 0,
            fRealQuantity = item.fRefuseQuantity > 0 ? it.iQuantity - item.fRefuseQuantity: it.iQuantity,
           fValidQuantity = item.fRefuseQuantity > 0 ? it.iQuantity - item.fRefuseQuantity: it.iQuantity,
        })
        .Where(it => it.ID == vouch.ID && it.cInvCode == item.cInvCode && (it.cBatch ?? "") == (item.cBatch ?? ""))
        .ExecuteCommand();

                        }
                    }



                    //先读取所涉及的到货单
                    var group = model.itemList.GroupBy(x => x.cArrCode).ToList();
                    foreach (var itemarr in group)
                    {
                        //到货单号
                        string cCode = itemarr.Key;
                        
                        //检查是否还有未检验的数据
                        var list = db.Queryable<PU_ArrivalVouchs>()
                            .InnerJoin<PU_ArrivalVouch>((x,y)=>x.ID==y.ID)
                            .InnerJoin<Inventory>((x,y,i) => x.cInvCode == i.cInvCode)
                            .Where((x, y, i) => y.cCode == cCode   && i.cInvDefine2=="是" && ( x.cDefine25 == null || (x.cDefine25 != "合格" && x.cDefine25 != "不合格")) ).ToList();
                        //当前单据已全部检验，则审核到货单
                        if (list.Count == 0)
                        { 
                            //审核
                            var result = db.Updateable<PU_ArrivalVouch>()
                            .SetColumns(it => new PU_ArrivalVouch
                            {
                                cverifier = "SDC",
                                cAuditDate = DateTime.Now.Date,
                                caudittime = DateTime.Now,
                                iverifystateex=2
                            }
                            )
                             .Where(it => it.cCode == cCode && (it.cverifier == "" || it.cverifier == null)) 
                            .ExecuteCommand();
                        }

                    }
                }


                return  DBService.ReOKObject("回写完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion

        #region 调拨单检验结果返回
        /// <summary>
        /// 调拨申请
        /// </summary>
        /// <param name="model">检验结果</param> 
        /// <returns></returns>
        public RetModel2 STTVQC(NBHF_QCCheck model)
        {
            try
            {
                if (model == null)
                {
                    throw new Exception("传入参数为空，错误");
                }
                if (model.itemList == null)
                {
                    throw new Exception("没有检验明细，错误");
                }
                if (model.itemList.Count == 0)
                {
                    throw new Exception("没有检验明细，参数错误");
                }

                //查询主表，构建
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {


                    foreach (var item in model.itemList)
                    {
                        //到货单号
                        string cCode = item.cTVCode;
                        if (string.IsNullOrEmpty(cCode))
                        {
                            throw new Exception("调拨单号不能为空");
                        }

                        TransVouch vouch = db.Queryable<TransVouch>().Where(x => x.cTVCode== cCode).First();
                        if (vouch == null)
                        {
                            throw new Exception("单据号错误");
                        }
                        //else if (!string.IsNullOrEmpty(vouch.cVerifyPerson))
                        //{
                        //    throw new Exception("单据已审核");
                        //}
                        else
                        {

                            //已拒收数量为基准进行反算
                            var result = db.Updateable<TransVouchs>()
         .SetColumns(it => new TransVouchs
         {
             cDefine26 = (double?)it.iTVQuantity,
             cDefine27 = (double?)item.fRefuseQuantity,
             //iTVQuantity = ( it.iTVQuantity - item.fRefuseQuantity),
             cDefine25 = "已检验"
         })
         .Where(it => it.ID == vouch.ID && it.cInvCode == item.cInvCode && (it.cTVBatch ?? "") == (item.cBatch ?? ""))
         .ExecuteCommand();

                        }
                    }



                    //先读取所涉及的到货单
                    var group = model.itemList.GroupBy(x => x.cArrCode).ToList();
                    foreach (var itemarr in group)
                    {
                        //到货单号
                        string cCode = itemarr.Key;

                        //检查是否还有未检验的数据
                        var list = db.Queryable<TransVouchs>()
                            .InnerJoin<TransVouch>((x, y) => x.ID == y.ID)
                            .Where((x, y) => y.cTVCode == cCode && (x.cDefine25 == null || x.cDefine25 != "已检验")).ToList();
                        //当前单据已全部检验，则审核到货单
                        if (list.Count == 0)
                        {
                            //审核
                            var result = db.Updateable<TransVouch>()
                            .SetColumns(it => new TransVouch
                            {
                                cVerifyPerson = "SDC",
                                dVerifyDate = DateTime.Now.Date,
                                dnverifytime = DateTime.Now, 
                            }
                            )
                             .Where(it => it.cTVCode == cCode)
                            .ExecuteCommand();
                        }

                    }
                }


                return DBService.ReOKObject("回写完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion


        #region 发货单检验结果返回
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="model">检验结果</param> 
        /// <returns></returns>
        public RetModel2 SADispatchQC(NBHF_QCCheck model)
        {
            try
            {
                if (model == null)
                {
                    throw new Exception("传入参数为空，错误");
                }
                if (model.itemList == null)
                {
                    throw new Exception("没有检验明细，错误");
                }
                if (model.itemList.Count == 0)
                {
                    throw new Exception("没有检验明细，参数错误");
                }

                //查询主表，构建
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {


                    foreach (var item in model.itemList)
                    {
                        //发货单号
                        string cCode = item.cDLCode;
                        if (string.IsNullOrEmpty(cCode))
                        {
                            throw new Exception("发货单号不能为空");
                        }

                        DispatchList vouch = db.Queryable<DispatchList>().Where(x => x.cDLCode == cCode).First();
                        if (vouch == null)
                        {
                            throw new Exception("单据号错误");
                        }
                        //else if (!string.IsNullOrEmpty(vouch.cVerifier))
                        //{
                        //    throw new Exception("单据已审核");
                        //}
                        else
                        {

                            //已拒收数量为基准进行反算

                            var result = db.Updateable<DispatchLists>()
         .SetColumns(it => new DispatchLists
         {
             cDefine26 = (double?)it.iQuantity,
             cDefine27 = (double?)item.fRefuseQuantity,
             //iQuantity = (it.iQuantity - item.fRefuseQuantity),
             cDefine25 = "已检验"
         })
         .Where(it => it.DLID == vouch.DLID && it.cInvCode == item.cInvCode && (it.cBatch ?? "") == (item.cBatch ?? "") )
         .ExecuteCommand();

                        }
                    }

                    //先读取所涉及的发货单
                    var group = model.itemList.GroupBy(x => x.cArrCode).ToList();
                    foreach (var itemarr in group)
                    {
                        //发货单号
                        string cCode = itemarr.Key;

                        //检查是否还有未检验的数据
                        var list = db.Queryable<DispatchLists>()
                            .InnerJoin<DispatchList>((x, y) => x.DLID == y.DLID)
                            .Where((x, y) => y.cDLCode == cCode && (x.cDefine25 == null || x.cDefine25 != "已检验")).ToList();
                        //当前单据已全部检验，则审核发货单
                        if (list.Count == 0)
                        {
                            //审核
                            var result = db.Updateable<DispatchList>()
                            .SetColumns(it => new DispatchList
                            {
                                cVerifier = "SDC",
                                dverifydate = DateTime.Now.Date,
                                dverifysystime = DateTime.Now,
                            }
                            )
                             .Where(it => it.cDLCode == cCode && (it.cVerifier == "" || it.cVerifier == null))
                            .ExecuteCommand();
                        }

                    }
                }


                return DBService.ReOKObject("回写完成");
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion

        #region 读取MES工单设备
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="model">检验结果</param> 
        /// <returns></returns>
        public RetModel2 GetMachine(NBHF_MachineQuery model)
        {
            try
            {
               NBHF_SDC_ReConent  ret= Get<NBHF_MachineQuery>("工单设备", model);
                if (ret.succeeded)
                {
                    return DBService.ReOKObject(ret.data);
                }
                else
                {
                    return DBService.ReErrObject(ret.errors);
                } 
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion

        #region 读取MES工时
        /// <summary>
        /// 生成BOM
        /// </summary>
        /// <param name="model">检验结果</param> 
        /// <returns></returns>
        public RetModel2  GetWorkHour(string cMonth)
        {
            try
            {
                NBHF_SDC_ReConent ret = Get<String>("工时", cMonth);


                if (ret.succeeded)
                {
                    //写入U8后台 
                     NBHF_WorkHour nBHF_WorkHour = JsonConvert.DeserializeObject<NBHF_WorkHour>(ret.data.ToString());
                    if (!string.IsNullOrWhiteSpace(nBHF_WorkHour.cMonth) && nBHF_WorkHour.itemList != null)
                    {

                        //查询主表，构建
                        using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                        {
                            ConnectionString = conStr,
                            DbType = SqlSugar.DbType.SqlServer,
                            IsAutoCloseConnection = true
                        }))
                        {
                            //先删除当前月份的工时 
                            db.Deleteable<Zdy_NBHF_WorkHour>().Where(x => x.cMonth == nBHF_WorkHour.cMonth);
                            foreach (NBHF_WorkHours item in nBHF_WorkHour.itemList)
                            {
                                db.Insertable(new Zdy_NBHF_WorkHour()
                                {
                                    dDate = DbHelper.GetDbDate(nBHF_WorkHour.cMonth.Substring(0, 4) + nBHF_WorkHour.cMonth.Substring(4, 2) + "-01"),
                                    cMonth = nBHF_WorkHour.cMonth,
                                    cMoCode = item.WokerOrderCode,
                                    dWorkHour = item.iSumWorkTime,
                                    cMaker = "SDC",
                                    dMaketime = DateTime.Now,
                                    cStatus = "未审核"
                                }).ExecuteCommand();
                            }
                        }
                        return DBService.ReOKObject("完成");
                    }
                    else
                    {
                        return DBService.ReOKObject("没有工时数据");
                    }
                   
                }
                else
                {
                    return DBService.ReErrObject(ret.errors);
                }
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }
        #endregion



        #region 写到入库通知单表
        /// <summary>
        /// 生成产成品入库单
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public RetModel2 ST_Rd10ByMO(HuaJinRdrecord model, int bRed)
        {
            try
            {
                string conStr = CanShu.conStr;

                if (model.itemList.Count == 0)
                {
                    throw new Exception("没有明细数据，无法保存");
                }
               
                RetModel retModel = new RetModel();

                //检查是否存在
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                   List<ZDY_RDRECORDS_ORI> lst  = db.Queryable<ZDY_RDRECORDS_ORI>().Where(x =>x.cType=="入库申请单" && x.cSourceCode == model.cCode ).ToList();
                    
                    if (lst.Count>0)
                    {
                        //检查U8里是否有，是否已经生成产成品入库单
                        string cparentid = lst[0].PARENTID;
                        string sql = string.Format("select count(*) sl from rdrecord10 where cdefine10='{0}'", cparentid);
                        int icnt = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                        if (icnt> 0)
                        {
                            return DBService.ReErrObject("入库单号已存在");
                        }
                        else
                        {
                            //删除中间表-入库申请单
                           int ire =  db.Deleteable<ZDY_RDRECORDS_ORI>().Where(x => x.cType == "入库申请单" && x.cSourceCode == model.cCode).ExecuteCommand();
                            if (ire==0)
                            {
                                return DBService.ReErrObject("入库单号已存在，覆盖失败");
                            }
                        }
                    }

                    //检查生产订单号是否存在

                    //检查存货编码是否正确

                    //检查已入库数量是否超出

                }
                string cParentid = "";
                //保存条码原始数据
                RetModel2 retinfo = SaveOriInfo(model);
                if (retinfo.code != 200)
                {
                    throw new Exception("保存出错：" + retinfo.message);
                }
                else
                {
                    cParentid = DbHelper.GetDbString(retinfo.data);
                }
                 

                    return DBService.ReOKObject( DbHelper.GetDbString(cParentid));
               

              

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }




        }

        private RetModel2 SaveOriInfo(HuaJinRdrecord vouch)
        {
            //插入标记
            string cParentid = System.Guid.NewGuid().ToString();
            List<ZDY_RDRECORDS_ORI> lst = new List<ZDY_RDRECORDS_ORI>();
            for (int i = 0; i < vouch.itemList.Count; i++)
            {
                if (DbHelper.GetDbInt(vouch.itemList[i].iQuantity) != 0)
                {
                    ZDY_RDRECORDS_ORI rd = new ZDY_RDRECORDS_ORI();
                    rd.PARENTID = cParentid;
                    rd.cSourceCode =vouch.cCode;
                    rd.cInvCode = vouch.itemList[i].cInvCode;
                    rd.cBatch = vouch.itemList[i].cBatch;
                    rd.iQuantity = DbHelper.GetDbdecimal(vouch.itemList[i].iQuantity);
                    rd.cType = "入库申请单";
                    rd.cMaker = vouch.cMaker;
                    rd.dDate =DbHelper.GetDbDate(vouch.dDate);
                    rd.cWhCode = vouch.cWhCode;
                    //rd.cPosCode = vouch.itemList[i].cPosCode;
                    //rd.cPosName = cPosName;
                    //rd.cCusCode = cCusCode;
                    rd.cWhCode = vouch.cWhCode;
                    rd.cRdCode = vouch.cRdCode;
                    if(!string.IsNullOrEmpty(vouch.itemList[i].dMDate))
                    {
                        rd.dMakeDate =DbHelper.GetDbDate(vouch.itemList[i].dMDate);
                    }
                    if (!string.IsNullOrEmpty(vouch.itemList[i].dVDate))
                    {
                        rd.dVDate = DbHelper.GetDbDate(vouch.itemList[i].dVDate);
                    }
                   
                    rd.cDefine1 = vouch.itemList[i].cMoCode; 
                    rd.dMaketime = DateTime.Now;

                    lst.Add(rd);
                }
            }
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                var cnt = db.Insertable(lst) //插入1层 Root->Books
     .ExecuteCommand();
                if (cnt == 0)
                {
                    return DBService.ReErrObject("未保存成功，请重试");
                }
                else
                {
                    return DBService.ReOKObject(cParentid);
                }
            }
        }
        #endregion
    }
}
